<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>性能对比：Scroll事件 vs IntersectionObserver</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
        }
        .container {
            display: flex;
            gap: 30px;
            margin-top: 30px;
        }
        .demo-section {
            flex: 1;
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }
        h1, h2 {
            text-align: center;
            color: white;
            margin-bottom: 10px;
        }
        h2 {
            color: #333;
            margin-top: 0;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }
        .image-container {
            height: 500px;
            overflow-y: auto;
            border: 2px solid #eee;
            border-radius: 8px;
            padding: 10px;
            margin-top: 15px;
        }
        .lazy-image {
            width: 100%;
            height: 200px;
            background: linear-gradient(45deg, #f0f0f0, #e0e0e0);
            border-radius: 6px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
            font-weight: bold;
            transition: all 0.3s ease;
        }
        .lazy-image.loaded {
            background: #d4edda;
            color: #155724;
            transform: scale(0.98);
        }
        .stats {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
            font-family: 'Courier New', monospace;
        }
        .stats div {
            margin: 5px 0;
        }
        .performance-warning {
            color: #dc3545;
            font-weight: bold;
        }
        .performance-good {
            color: #28a745;
            font-weight: bold;
        }
        .trigger-count {
            font-size: 1.2em;
            font-weight: bold;
        }
        .comparison-summary {
            background: white;
            padding: 20px;
            border-radius: 12px;
            margin-top: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }
        .badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 0.8em;
            font-weight: bold;
            margin-left: 8px;
        }
        .badge-bad {
            background: #dc3545;
            color: white;
        }
        .badge-good {
            background: #28a745;
            color: white;
        }
    </style>
</head>
<body>
    <h1>🚀 Scroll事件 vs IntersectionObserver API 性能对比</h1>
    
    <div class="container">
        <!-- 传统 Scroll 事件实现 -->
        <div class="demo-section">
            <h2>传统 Scroll 事件 <span class="badge badge-bad">性能消耗大</span></h2>
            <div class="image-container" id="scrollContainer">
                <div id="scrollImages"></div>
            </div>
            <div class="stats">
                <div>Scroll事件触发次数: <span id="scrollCount" class="trigger-count">0</span></div>
                <div class="performance-warning">主线程计算: 频繁执行</div>
                <div>已加载图片: <span id="scrollLoaded">0</span>/20</div>
            </div>
        </div>

        <!-- Intersection Observer 实现 -->
        <div class="demo-section">
            <h2>IntersectionObserver API <span class="badge badge-good">高效节能</span></h2>
            <div class="image-container" id="observerContainer">
                <div id="observerImages"></div>
            </div>
            <div class="stats">
                <div>回调触发次数: <span id="observerCount" class="trigger-count">0</span></div>
                <div class="performance-good">主线程计算: 按需执行</div>
                <div>已加载图片: <span id="observerLoaded">0</span>/20</div>
            </div>
        </div>
    </div>

    <div class="comparison-summary">
        <h3>🎯 性能对比总结</h3>
        <p><strong>传统 Scroll 事件的问题：</strong></p>
        <ul>
            <li>Scroll 事件每秒可能触发数十次，无论是否需要</li>
            <li>每次都需要执行 getBoundingClientRect()，引发重排（Reflow）</li>
            <li>大量计算阻塞主线程，导致页面卡顿</li>
        </ul>
        <p><strong>IntersectionObserver 的优势：</strong></p>
        <ul>
            <li>浏览器原生支持，计算在单独的线程中进行</li>
            <li>只在交叉状态变化时触发回调，极大减少执行次数</li>
            <li>不会引起重排，性能开销极小</li>
        </ul>
    </div>

    <script>
        // 生成图片占位符
        function generateImagePlaceholders(containerId, count) {
            const container = document.getElementById(containerId);
            for (let i = 0; i < count; i++) {
                const imgDiv = document.createElement('div');
                imgDiv.className = 'lazy-image';
                imgDiv.innerHTML = `图片 ${i + 1}<br><small>未加载</small>`;
                imgDiv.dataset.src = `https://picsum.photos/400/200?random=${i}`;
                container.appendChild(imgDiv);
            }
        }

        // 初始化图片
        generateImagePlaceholders('scrollImages', 20);
        generateImagePlaceholders('observerImages', 20);

        // 图片加载函数
        function loadImage(imgElement) {
            if (imgElement.classList.contains('loaded')) return;  // 如果imgElement有loaded类名，那么代码就不会继续往下执行了
            
            imgElement.classList.add('loaded');  // 给imgElement添加loaded类名，代表该元素已经被加载，这里的imgElement其实就是动态创建的lazy-image
            setTimeout(() => {
                imgElement.innerHTML = '';
                imgElement.style.backgroundImage = `url(${imgElement.dataset.src})`;  // 注意：这里才会触发资源的加载
                imgElement.style.backgroundSize = 'cover';
                imgElement.style.backgroundPosition = 'center';
            }, 300);
        }

        // 传统 Scroll 事件实现
        const scrollContainer = document.getElementById('scrollContainer');
        const scrollImages = scrollContainer.querySelectorAll('.lazy-image');
        let scrollTriggerCount = 0;  //用来记录scroll触发的次数
        let scrollLoadedCount = 0;  // 用来记录加载完成的图片的数量，也就是

        function checkInViewportScroll() {
            scrollTriggerCount++;
            document.getElementById('scrollCount').textContent = scrollTriggerCount;
            
            const containerRect = scrollContainer.getBoundingClientRect();
            
            scrollImages.forEach((img, index) => {
                if (img.classList.contains('loaded')) return;  // 图片是否被加载过了
                
                const imgRect = img.getBoundingClientRect();  // 获取图片的集合信息，例如top 200px 代表相对于视口顶部200px的位置，bottom 0px代表处于视口底部的位置
                const isInViewport = (
                    imgRect.top >= containerRect.top &&
                    imgRect.bottom <= containerRect.bottom
                );  // 通过图片的top和bottom属性是来确定图片是否已经出现在容器内
                
                if (isInViewport) {
                    loadImage(img);
                    scrollLoadedCount++;
                    document.getElementById('scrollLoaded').textContent = scrollLoadedCount;
                }
            });
        }

        scrollContainer.addEventListener('scroll', checkInViewportScroll);
        // 初始检查一次
        setTimeout(checkInViewportScroll, 100);

        // Intersection Observer 实现
        const observerContainer = document.getElementById('observerContainer');
        const observerImages = observerContainer.querySelectorAll('.lazy-image');
        let observerTriggerCount = 0;
        let observerLoadedCount = 0;

        const observer = new IntersectionObserver((entries) => {
            observerTriggerCount++;
            document.getElementById('observerCount').textContent = observerTriggerCount;
            
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    loadImage(entry.target);
                    observerLoadedCount++;
                    document.getElementById('observerLoaded').textContent = observerLoadedCount;
                    observer.unobserve(entry.target);  // 核心，当前entire已经出现在了 root: observerContainer 区域内，就将它取消观察
                }
            });
        }, {
            root: observerContainer,
            threshold: 0.1
        });

        // 开始观察所有图片
        observerImages.forEach(img => observer.observe(img));

        

        // 添加重置功能用于演示
        setTimeout(() => {
            scrollContainer.scrollTop = 0;
            observerContainer.scrollTop = 0;
        }, 2000);
    </script>
</body>
</html>